//
//  WYMOauthrController.swift
//  iOS11weibo
//
//  Created by 王应明 on 16/7/24.
//  Copyright © 2016年 DescendantsOftheSun. All rights reserved.
//

import UIKit
import SVProgressHUD

class WYMOauthrController: UIViewController {
    
    override func loadView() {
        super.loadView()
        self.view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let URLString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let URL = NSURL(string: URLString)
        let request = NSURLRequest(URL: URL!)
        webView.loadRequest(request)
        SVProgressHUD.setMinimumDismissTimeInterval(2)
        //       SVProgressHUD.showErrorWithStatus("真正加载...")
        SVProgressHUD.showWithStatus("正在加载....")
        self.view.backgroundColor = UIColor.whiteColor()
        setupNavigaitonBar()
    }
    
    private func setupNavigaitonBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(WYMOauthrController.autoFill))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(NSStream.close))
        self.navigationItem.title = "登录"
        
    }
    //MARK:---按钮点击事件
    @objc private func autoFill() {
        //填充
        //        document.getElementById('userId').value="wangyingming89@163.com"
        //        document.getElementById('passwd').value = 'wym+232036'
        print(#function)
        let jsCode = "document.getElementById('userId').value='wangyingming89@163.com';document.getElementById('passwd').value = 'wym+232036'"
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    
    @objc private func close() {
        //关闭控制器
        print(#function)
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK:---懒加载
    private lazy var webView: UIWebView = UIWebView()
    
}

extension WYMOauthrController: UIWebViewDelegate {
    //webview代理方法加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //每当webview要去加载一个网页都会调用这个方法，询问我们是否真的要去加载返回false就加载，返回ture就不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        print("加载的地址\(urlString)")
        //拦截授权回调地址
        //hasPrefix 是前缀
        if !urlString.hasPrefix(redirect_uri) {
            //不是授权回调地址,放过去加载
            return true
        } else {
            //点击取消和授权都会加载授权回调地址
            //取消:http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
            //授权:http://www.baidu.com/?code=73b070d569faf93a9b395a0eac823a0c
            //?后面的东西叫query
            //区分 取消按钮和授权按钮，看？后面是否以code=开头
            let query = request.URL!.query!
            print("query:\(query)")
            let codeString = "code="
            if query.hasPrefix(codeString) {
                //                print("点击了确定授权")
                //截取code=后面的字符串
                let nsQuery = query as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                
                //发送poset请求
                WYMUserAccountViewModel .sharedUserAccountViewModel.loadAccessToken(code, completion: { (error: NSError?) -> Void in
                    //保存账号后调用
                    if error != nil {
                        SVProgressHUD.showErrorWithStatus("加载AccessToken出错了")
                        //延迟关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), {
                            self.close()
                        })
                        
                        return
                    }
                    //保存账号后调用关闭界面
                    self.close()
                })
                
            } else {
                //                print("点击了取消授权")
                self.close()
            }
            
            return false
        }
    }
    //去服务器请求AccessToken
    //    private func loadAccessToken(code: String) {
    //        let URLString = "https://api.weibo.com/oauth2/access_token"
    //        //参数
    //        let parmaeters = [
    //            "client_id": client_id,
    //            "client_secret": client_secret,
    //            "grant_type": "authorization_code",
    //            "code": code,
    //            "redirect_uri": redirect_uri
    //        ]
    //
    //        WYMNetworkTool.sharedNetworkTool.POST(URLString, parameters: parmaeters, progress: nil, success: { (_, resopnseOjbect) -> Void in
    ////            print("成功的回调\(resopnseOjbect)")
    //
    //            let dict = resopnseOjbect as! [String: AnyObject]
    //            //字典转模型
    //            let userAccount = WYMUserAccount(dict: dict)
    //            print("userAccount:\(userAccount)")
    //
    //            //保存到沙盒中
    //
    //            //读取沙盒的模型
    //            
    //            }) { (_, error) -> Void in
    //                print("失败的回调\(error)")
    //        }
    //        
    //    }
    //    
}